<template>
  <view class="address-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">收货地址</text>
    </view>

    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view 
        class="address-item" 
        :class="{ selected: selectMode && selectedAddressId === address.id }"
        v-for="address in addressList" 
        :key="address.id"
        @tap="selectAddress(address)"
      >
        <!-- 选择模式的选中标识 -->
        <view class="select-indicator" v-if="selectMode">
          <view class="radio" :class="{ checked: selectedAddressId === address.id }">
            <text class="radio-icon" v-if="selectedAddressId === address.id">✓</text>
          </view>
        </view>
        
        <view class="address-content">
          <view class="address-header">
            <text class="contact-name">{{ address.receiverName }}</text>
            <text class="contact-phone">{{ address.receiverPhone }}</text>
            <view class="default-badge" v-if="address.isDefault">
              <text class="badge-text">默认</text>
            </view>
          </view>
          
          <text class="address-detail">{{ address.provinceName + address.cityName + address.districtName + (address.street ? address.street : '') + address.detailAddress }}</text>
          
          <view class="address-actions" v-if="!selectMode">
            <view class="action-btn" @tap.stop="editAddress(address)">
              <text class="action-text">编辑</text>
            </view>
            <view class="action-btn" @tap.stop="deleteAddress(address.id)">
              <text class="action-text delete">删除</text>
            </view>
            <view class="action-btn" @tap.stop="setDefault(address.id)" v-if="!address.isDefault">
              <text class="action-text">设为默认</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="addressList.length === 0">
      <text class="empty-icon">📍</text>
      <text class="empty-text">暂无收货地址</text>
      <text class="empty-desc">请添加您的收货地址</text>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="add-btn" @tap="addAddress" v-if="!selectMode">
        <text class="btn-text">+ 新增地址</text>
      </view>
      
      <view class="confirm-btn" @tap="confirmSelect" v-if="selectMode">
        <text class="btn-text">确认选择</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import api from '@/utils/api.js'
import storageUtil from '@/utils/storage'
// 响应式数据
const addressList = ref([])
const selectMode = ref(false)
const selectedAddressId = ref(null)
const loading = ref(false)

// 加载地址列表
const loadAddressList = async () => {
  loading.value = true
  try {
    // 获取openId
    const openId = uni.getStorageSync('openid')
    if (!openId) {
      uni.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      })
      loading.value = false
      return
    }
    
    const res = await api.address.getAddressList(openId)
    console.log('地址列表：', res)
    
    if (res.code === 0 && res.data) {
      // 直接使用返回的数据
      addressList.value = res.data
    } else {
      addressList.value = []
    }
  } catch (error) {
    console.error('加载地址列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
    addressList.value = []
  } finally {
    loading.value = false
  }
}

// 选择地址
const selectAddress = (address) => {
  if (selectMode.value) {
    selectedAddressId.value = address.id
  }
}


// 确认选择
const confirmSelect = () => {
  if (!selectedAddressId.value) {
    uni.showToast({
      title: '请选择地址',
      icon: 'none'
    })
    return
  }
  
  const selectedAddress = addressList.value.find(addr => addr.id === selectedAddressId.value)
  // 返回上一页并传递选中的地址
  storageUtil.address.setSelectedAddress(selectedAddress)
  uni.navigateBack()
}

// 新增地址
const addAddress = () => {
  uni.navigateTo({
    url: '/pages/address/edit'
  })
}

// 编辑地址
const editAddress = (address) => {
  uni.navigateTo({
    url: `/pages/address/edit?id=${address.id}`
  })
}

// 删除地址
const deleteAddress = (addressId) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个地址吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await api.address.deleteAddress(addressId)
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            // 重新加载地址列表
            loadAddressList()
          } else {
            uni.showToast({
              title: result.message || '删除失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('删除地址失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 设为默认地址
const setDefault = async (addressId) => {
  try {
    const result = await api.address.setDefaultAddress(addressId)
    if (result.code === 0) {
      uni.showToast({
        title: '设置成功',
        icon: 'success'
      })
      // 重新加载地址列表
      loadAddressList()
    } else {
      uni.showToast({
        title: result.message || '设置失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    uni.showToast({
      title: error.message || '设置失败',
      icon: 'none'
    })
  }
}

// 生命周期
onLoad((options) => {
  selectMode.value = options.mode === 'select'
  selectedAddressId.value = options.selectedId
  console.log('已选择的地址id:', selectedAddressId.value)
  loadAddressList()
})

// 页面显示时刷新列表
uni.$on('addressUpdated', () => {
  loadAddressList()
})
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 页面标题 */
.page-header {
  background: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 地址列表 */
.address-list {
  padding: 16px;
}

.address-item {
  background: white;
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 2px solid transparent;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  transition: all 0.3s ease;
}

.address-item.selected {
  border-color: #FFB800;
  background: #FFF8E1;
}

.select-indicator {
  flex: 0 0 auto;
  padding-top: 2px;
}

.radio {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio.checked {
  border-color: #FFB800;
  background: #FFB800;
}

.radio-icon {
  font-size: 12px;
  color: white;
  font-weight: bold;
}

.address-content {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.contact-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.contact-phone {
  font-size: 14px;
  color: #666;
}

.default-badge {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 7rpx;
}

.badge-text {
  font-size: 20rpx;
  color: white;
  font-weight: bold;
}

.address-detail {
  display: block;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 12px;
}

.address-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  padding: 4px 0;
}

.action-text {
  font-size: 14px;
  color: #FFB800;
}

.action-text.delete {
  color: #FF6B6B;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  display: block;
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  display: block;
  font-size: 16px;
  color: #999;
  margin-bottom: 8px;
}

.empty-desc {
  display: block;
  font-size: 14px;
  color: #ccc;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.add-btn,
.confirm-btn {
  background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
  border-radius: 24px;
  padding: 14px 24px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(255, 184, 0, 0.3);
  transition: all 0.3s ease;
}

.add-btn:active,
.confirm-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(255, 184, 0, 0.3);
}

.btn-text {
  font-size: 16px;
  color: white;
  font-weight: bold;
}
</style>